// 引入axios以及element ui中的loading和message组件
import axios from 'axios'
import store from '../store'
import router from '../router/router';
// import {getToken, setToken, removeToken} from '@/util/auth';
import {Message, Notification} from 'element-ui';
import {baseUrl} from '@/config/env'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style


axios.defaults.timeout = 60000;
axios.defaults.withCredentials = true;  //跨域请求，允许保存cookie
axios.defaults.baseURL = baseUrl;       // baseUrl
NProgress.configure({showSpinner: false})// NProgress Configuration

//HTTPrequest拦截
axios.interceptors.request.use(config => {
  NProgress.start()

  // start progress bar
  // if (store.getters.token) {
  // 	config.headers['X-Token'] = getToken()
  // }

  return config
}, error => {
  console.log('err:' + error)// for debug
  return Promise.reject(error)
})


//HTTPresponse拦截
axios.interceptors.response.use(response => {
  NProgress.done();
  let code = response.data.code;
  if (code != 200) {
    Notification({
      title: "错误 " + code,
      message: response.data.msg,
      type: "error",
      duration: 2000
    })
  }
  return response.data
}, error => {
  NProgress.done();
  let errMsg = error.toString();
  // let code = errMsg.substr(errMsg.indexOf('code') + 5);
  Message({
    message: errMsg,
    type: 'error'
  });
  return Promise.reject(new Error(error));
})

export default axios
